@extends('layouts.app')
@section('title'){{$topic->title}}-@parent @endsection
@section('description'){!! trim(str_replace('&nbsp;','',\gl\str_ellipsis(strip_tags($topic->body),400))) !!} @endsection
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-9 col-md-9 topic-list">
                <template v-if="info != ''">
                    <div class="card">
                        <div class="card-header bg-white">
                            <h1 class="text-center">@{{ info.title }}</h1>
                            <div class="article-meta text-center">
                                <span class="font-weight-light">@{{ info. created_at}}</span>
                                ⋅
                                <template v-if="info.reply_count">
                                    <i class="icon-comment"></i>
                                    <span class="font-weight-light">@{{info.reply_count}}</span>
                                    ⋅
                                </template>
                                <template v-if="info.view_count">
                                    <i class="icon-eye-open"></i>
                                    <span class="font-weight-light">@{{ info.view_count }} 阅读</span>
                                </template>

                            </div>
                        </div>
                        <div class="card-body" v-html=" info.body ">
                        </div>
                        <div class="card-footer">
                            @can('update',$topic)
                                <a type="button" class="btn edit" :href="'/topics/form/' + info.id" ><i class=" icon-edit"></i>编辑</a>
                            @endcan
                            @can('setTop',$topic)
                                <a type="button" class="btn edit" :href="'/topics/set_top' + info.id" >
                                    @if($topic->order == -1)
                                        <i class="icon-reply"></i>撤销置顶
                                    @else
                                        <i class="icon-arrow-up"></i>置顶
                                    @endif
                                </a>
                            @endcan
                            @can('delete',$topic)
                                <a class="btn btn-danger" href="javascript:;" @click="del(info.id)"><i class="icon-trash icon-large"></i> 删除</a>
                            @endcan
                        </div>
                    </div>
                </template>
                <div class="card" style="margin-top: 20px">

                        <div class="card-body">

                            <div class="reply-list" v-if="replies != ''">
                                <template v-for="item in replies">
                                    <div class="media">
                                        <div class="avatar pull-left">
                                            <a href="">
                                                <img :alt="item.user.name" :src="item.user.avatar" class="media-object img-thumbnail" style="width: 48px; height: 48px;">
                                            </a>
                                        </div>
                                        <div class="infos" style="width: 100%;">
                                            <div class="media-heading">
                                                <a href="" :title="item.user.name">
                                                    @{{item.user.name}}
                                                </a>
                                                <span> •  </span>
                                                <span :title="item.created_at" class="meta">@{{item.created}}</span>
                                                <span class="operate pull-right links" style="float:right;">
                                                    <a class="icon-reply" href="javascript:void(0)" @click="replyOne(item.user.id,item.user.name);" :title="'回复 '+ item.user.name"></a>
                                                    <template v-if="item.can_delete == true">
                                                        <a class="icon-trash icon-large" href="javascript:void(0);" @click="delReply(item.id)" title="删除"></a>
                                                        {{--<span> ⋅  </span>--}}
                                                    </template>
                                                </span>
                                            </div>
                                            <div class="reply-content" style="width: 100%">
                                                <span v-html="item.content"></span>
                                            </div>
                                        </div>
                                    </div>

                                    <hr>
                                </template>
                            </div>
                            <div class="reply-list" v-else><template v-if="empty_reply_msg">@{{empty_reply_msg}}</template></div>
                            <div id="pagination" class="panel-footer"></div>
                        </div>
                    </div>

                <div class="card" style="margin-top: 20px">
                    <div class="reply-box">
                        <div class="form-group">
                            <textarea style="display: none;" class="form-control" v-model="reply_content" ></textarea>
                            <div id="toolbar-container"></div>
                            <div id="editor" style="border: solid 1px grey;"></div>
                        </div>
                        <button type="submit" @click="submit()" class="btn btn-primary btn-sm">
                            <i class="icon-comment"></i> 回复
                        </button>
                    </div>
                </div>
            </div>
            <template v-if="info !=''">
                <div class="col-lg-3 col-md-3">
                    <div class="card">
                        <div class="card-body links">
                            <div class="text-center">作者：@{{ info.user_name }}</div>
                            <hr>
                            <div class="media">
                                <div align="center">
                                    <a :href="/user/ + info.user_id">
                                        <img :src="info.user_avatar" class="img-thumbnail img-fluid">
                                    </a>
                                </div>
                            </div>
                            <hr>
                            <div class="media-body">
                                <h4><strong>个人简介</strong></h4>
                                <p>
                                    <template v-if="info.user_introduction">
                                        @{{ info.user_introduction }}
                                    </template>
                                    <template v-else>
                                        这个人很懒，什么都没有写
                                    </template>
                                </p>
                            </div>
                            <hr>

                            <div class="media-body">
                                <h4><strong>注册于</strong></h4>
                                <p>@{{ info. user_created_at}}</p>
                            </div>

                        </div>
                    </div>
                </div>
            </template>
        </div>
        <confirm-component ref="confirm"></confirm-component>
    </div>
@endsection

@section('scripts')
    <script src="{{asset('plugins/ckeditor5-build-decoupled-document/ckeditor.js')}}"></script>
    <script src="{{asset('js/editor/FileUploadAdapter.js')}}"></script>
    <script>
        var id = '{{$id}}';
        new Vue({
            el:'#app',
            mounted() {
                this.setInfo(id);

            },
            data() {
                return {
                    'info':'',
                    reply_content:'',
                    reply_users:[],
                    replies:'',
                    empty_reply_msg:'正在加载评论，请稍后...',
                    page:{
                        'curr_page':'',
                        'total_page':'',
                        'size':''
                    }
                }
            },
            methods:{
                setInfo(id) {
                    axios.get('/get_topicjson/' + id).then((response) => {
                        this.info = response.data;
                        this.createEditor();
                        this.getReplies();
                        this.paginate();
                    }).catch((error) => {
                        console.log(error)
                    });
                },
                submit() {
                    $('button[type="submit"]').attr('disabled',true)
                    this.reply_content = editor.getData();
                    if (!Func.delHtmlAndNbsp(this.reply_content)) {
                        $('button[type="submit"]').attr('disabled',false);
                        return false;
                    }
                    axios.post('/save_replies',{reply_content:this.reply_content, reply_users:this.reply_users, id:this.info.id, page_size:this.page.size}).then((response) => {
                        if (response.data.status == true) {
                            editor.setData('');
                            this.page.curr_page = response.data.total_page;
                            this.page.total_page = response.data.total_page;
                            this.info.reply_count = response.data.reply_count;
                            this.getReplies(this.page.total_page,this.page.size);
                            $("#pagination").whjPaging("setPage", this.page.curr_page, this.page.total_page);
                        } else {
                            alert(response.data.msg);
                        }
                        $('button[type="submit"]').attr('disabled',false);
                    }).catch((error) => {
                        console.log(error.response)
                        if (error.response.status == 422) {
                            this.form.errors = error.response.data.errors;
                        }
                        $('button[type="submit"]').attr('disabled',false);
                    });
                },
                getReplies(currPage,pageSize) {
                    if (!currPage) {
                        currPage = 0;
                    }
                    if (!pageSize) {
                        pageSize = 50;
                    }
                    axios.get('/replies/get?curr_page=' + currPage + '&page_size=' + pageSize + '&topic_id=' + id).then((response) => {
                        if (response.data.status == true) {
                            this.replies = response.data.replies;
                            if (this.replies.length === 0) {
                                this.empty_reply_msg = '暂无评论，快来成为第一个吧~';
                            } else {
                                this.empty_reply_msg = '正在加载评论，请稍后...';
                            }
                            this.page.total_page = response.data.total_page;
                            this.page.size = pageSize;
                            $("#pagination").whjPaging("setPage", this.page.curr_page, this.page.total_page);
                        }
                    }).catch((error) => {
                        console.log(error)
                    });
                },
                delReply(id) {
                    this.$refs.confirm.dialog('您确定要删除该评论吗？',() => {
                        axios.post('/replies/delete',{id:id}).then((response) =>{
                            if (response.data.status) {
                                this.info.reply_count = response.data.reply_count;
                                this.getReplies();
                            }
                        }).catch(function (error){
                            console.log(error)
                        });
                    },function(){

                    });
                },
                del(id){
                    this.$refs.confirm.dialog('您确定要删除该文章吗？',() => {
                        axios.post('/topics/delete',{id:id}).then((response) =>{
                            if (response.data.status) {
                                window.location.href = '/';
                                //this.getData();
                            }
                        }).catch(function (error){
                            console.log(error)
                        });
                    },function(){

                    });
                },
                replyOne(userId,userName) {
                    this.reply_users.push(userId);
                    var callUser = '<a href="/user/' + userId +'">@' + userName +'</a> &nbsp; ';
                    var callBody = callUser  + editor.getData();
                    editor.setData(callBody);
                    $("html,body").animate({scrollTop:$("#toolbar-container").offset().top},100);
                },
                paginate() {
                    var pageOptions = {
                        //可选，每页显示条数下拉框，默认下拉框5条/页(默认)、10条/页、15条/页、20条/页
                        pageSizeOpt: [
                            {'value': 5, 'text': '5条/页'},
                            {'value': 10, 'text': '10条/页'},
                            {'value': 15, 'text': '15条/页'},
                            {'value': 20, 'text': '20条/页'},
                            {'value': 50, 'text': '50/页','selected':true},
                        ],
                        //可选，css设置，可设置值：css-1，css-2，css-3，css-4，css-5，默认css-1，可自定义样式
                        css: 'css-4',
                        //可选，总页数
                        totalPage: this.page.total_page,
                        //可选，展示页码数量，默认5个页码数量
                        showPageNum: 5,
                        //可选，首页按钮展示文本，默认显示文本为首页
                        firstPage: '首页',
                        //可选，上一页按钮展示文本，默认显示文本为上一页
                        previousPage: '上一页',
                        //可选，下一页按钮展示文本，默认显示文本为下一页
                        nextPage: '下一页',
                        //可选，尾页按钮展示文本，默认显示文本为尾页
                        lastPage: '尾页',
                        //可选，跳至展示文本，默认显示文本为跳至
                        skip: '跳至',
                        //可选，确认按钮展示文本，默认显示文本为确认
                        confirm: '确认',
                        //可选，刷新按钮展示文本，默认显示文本为刷新
                        refresh: '刷新',
                        //可选，共{}页展示文本，默认显示文本为共{}页，其中{}会在js具体转化为数字
                        totalPageText: '共{}页',
                        //可选，是否展示首页与尾页，默认true
                        isShowFL: true,
                        //可选，是否展示每页N条下拉框，默认true
                        isShowPageSizeOpt: true,
                        //可选，是否展示跳到指定页数，默认true
                        isShowSkip: true,
                        //可选，是否展示刷新，默认true
                        isShowRefresh: true,
                        //可选，是否展示共{}页，默认true
                        isShowTotalPage: true,
                        //可选，是否需要重新设置当前页码及总页数，默认false，如果设为true，那么在请求服务器返回数据时，需要调用setPage方法
                        isResetPage: false,
                        //必选，回掉函数，返回参数：第一个参数为页码，第二个参数为每页显示N条
                        callBack: (currPage,pageSize) => {
                            this.page.curr_page = currPage;
                            this.page.size = pageSize;
                            this.getReplies(currPage,pageSize);
                        }
                    }
                    $("#pagination").whjPaging(pageOptions);
                },
                createEditor() {
                    DecoupledEditor
                        .create( document.querySelector( '#editor' ) ,{
                            toolbar: [ 'heading', '|', 'fontSize','fontFamily','bold', 'italic','underline','strikeThrough','highLight','alignment', 'link', 'bulletedList', 'numberedList', 'blockQuote','insertTable','undo','redo' ]
                        })
                        .then( editor => {
                            const toolbarContainer = document.querySelector( '#toolbar-container' );
                            toolbarContainer.appendChild( editor.ui.view.toolbar.element );
                            window.editor = editor;
                            editor.plugins.get('FileRepository').createUploadAdapter = (loader)=>{
                                return new FileUploadAdapter(loader);
                            };
                            if (!this.info.auth) {
                                editor.setData('登录后才能发表评论');
                                editor.isReadOnly=true
                                $('button[type="submit"]').attr('disabled',true);
                            } else {
                                editor.isReadOnly = false;
                                $('button[type="submit"]').attr('disabled',false);
                            }
                        } )
                        .catch( error => {
                            console.error( error );
                        } );

                }
            }
        });
    </script>
@endsection

